package com.amkai.aes.webservice.binary.objecthandler.inventory;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryElementCalculatorJob;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryElementCalculatorParameter;
import com.amkai.aes.aescommon.service.binary.job.inventory.InventoryElementCalculatorResult;
import com.amkai.aes.generatedbeans.inventory.InventoryElement;
import com.amkai.aes.generatedbeans.inventory.VendorOrderInformation;
import com.amkai.aes.generatedbeans.inventory.items.SupplyResourceItem;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class InventoryElementCalculatorHandler implements JobObjectHandler<InventoryElementCalculatorJob, InventoryElementCalculatorParameter, InventoryElementCalculatorResult> {

	private static final Log logger = LogFactory.getLog(InventoryElementCalculatorHandler.class);
	private static final String QUERY = " SELECT ie FROM InventoryElement ie ";

	@Override
	public InventoryElementCalculatorResult process(
			InventoryElementCalculatorJob job,
			InventoryElementCalculatorParameter object) {
		SessionManager sm = null;

		InventoryElementCalculatorResult result = new InventoryElementCalculatorResult();

		double average = 0;
		try {
			sm = SiteManager.Start();
			sm.openSession();

			Query query = sm.execute(QUERY);

			List<InventoryElement> ieList = query.list();

			for (InventoryElement ie : ieList) {

				//for (SupplyResourceItem suppItem : ie.getSupplyResourceItem()) {
				if (ie.getSupplyResourceItem() != null ){
					if (ie.getSupplyResourceItem().equals(object.getId())) {
							for (VendorOrderInformation vInf : ie.getVendorOrderInformations()) {
								average += vInf.getPricePerUsageUnit()
										.doubleValue();
							}
					}
				//}
				if ( ie.getVendorOrderInformations().size() != 0) {
					average = average / ie.getVendorOrderInformations().size();
				}
				}else{
					logger.equals("Inventory element id > " + ie.getId() + " not exist supplyResourceItem");
				}
			}

			logger.debug("average : " + average);
			result.setAverageResult(average);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			ex.printStackTrace();
		} finally {
			sm.closeSession();
		}
		return result;
	}

}
